<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\Target\facade\Target;
use app\common\model\Area;
use app\common\model\Relation;
use app\common\tool\Excel;
use think\App;
use think\Exception;
use think\facade\Cache;
use think\facade\View;
use think\response\Json;
use addons\Builder\facade\Builder;
use app\common\model\Assets;
use app\common\model\Level;
use app\common\model\Logs;
use think\exception\ValidateException;

class User extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    //验证器
    protected string $validate = 'User';

    //主模型
    protected string $model = '\app\common\model\User';

    //关联模型
    protected array $hasOne = ['level', 'assets', 'salesman'];

    protected array $append = ['minTeam'];

    protected array $sort = [
        'ordinary' => [
            'create_time' => 'desc'
        ],
        'formal'   => [
            'active_time' => 'desc'
        ]
    ];

//    //普通会员
    public function ordinary(): string
    {
        $binding = \app\common\model\Binding::where(['aid'=>$this->admin->id,'delete_time'=>0])->find();
        if($binding)
        {
            $ids = \app\common\model\User::where(['salesman_id'=>$binding->uid])->column('id');
            return $this->setTable([], [['id', 'in', $ids]],0);
        }else{
            return $this->setTable([
                'reset_2' => [
                    'title' => '重置支付密码',
                    'icon'  => 'layui-icon-password',
                    'url'   => url('user/reset', ['type' => 2])->build(),
                    'event' => '_batchSubmit'

                ],
                'import' => [
                    'title' => '导入',
                    'href' => url('import')->build(),
                    'class' => 'layui-btn layui-bg-cyan layui-btn-sm'
                ],
                'template' => [
                    'icon' => 'layui-icon-download-circle',
                    'title' => '下载模板'
                ],
                'export',
                'agent' => [
                    'title' => '分配业务员',
                    'icon'  => 'layui-icon-password',
                    'url'   => url('user/agent')->build(),
                    'width' => '30%',
                    'event' => '_batchNewPage'
                ]
            ], [],1);
        }
    }

    public function setTable($tb = [], $extra_map=[],$type=[]): string
    {
        //构建表格数据
        $table = Builder::Table()
            ->addColumn(['type' => 'checkbox', 'title' => '全选', 'fixed' => 'left'])
            ->addColumn(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80, 'fixed' => 'left'])
            ->addColumn(['field' => 'name', 'title' => '会员姓名', 'fixed' => 'left'])
            ->addColumn(['field' => 'code', 'title' => '会员编号', 'fixed' => 'left'])
            ->addColumn(['field' => 'name', 'title' => '投保人', 'modify' => '2,input', 'fixed' => 'left'])
            ->addColumn(['field' => 'mobile', 'title' => '手机号', 'modify' => '2,input', 'fixed' => 'left'])
//            ->addColumn(['field' => 'password', 'title' => '登录密码', 'placeholder' => ',默认111111', 'modify' => '1,password', 'hide' => 'true'])
            ->addColumn(['field' => 'pay_password', 'title' => '支付密码', 'placeholder' => ',默认222222', 'modify' => '1,password', 'hide' => 'true']);
//            ->addColumn(['field' => 'level_id', 'title' => '等级', 'modify' => '4,select,getLevel', 'templet' => '<span>{{d.level?d.level.title:"暂无"}}</span>'])
             if($type)
             {
                 $table->addColumn(['field' => 'salesman_id', 'title' => '业务员', 'modify' => '2,select,getSalesman', 'templet' => '<span>{{d.salesman?d.salesman.name:"暂无"}}</span>']);
             }
        //渲染账户
        foreach (Assets::getFields(3) as $k => $v) {
            $table->addColumn(['field' => $k, 'title' => $v, 'templet' => '<span>{{d.assets.' . $k . '}}</span>']);
        }
         $table->addColumn(['field' => 'create_time', 'title' => '注册时间', 'width' => 150]);
            if($type)
            {
                $table->addColumn(['field' => 'is_salesman', 'title' => '是否是业务员', 'templet' => '#is_salesman', 'width' => 120]);
            }

        return $table->addColumn(['field' => 'is_lock', 'title' => '锁定登录', 'templet' => '#is_lock', 'width' => 120])
            ->addColumn(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 200])
            ->addRightButtons(
                [
//                    'login' => ['title' => '登录', 'event' => '_submit', 'url' => url('user/login')->build()],
                    'edit'  => ['size' => '50%'],
                    'delete'
                ])
            ->addTopButtons(
                array_merge([],$tb))
            ->addSwitchTool([['name' => 'is_lock', 'pk' => $this->pk, 'text' => '锁定|正常'],['name' => 'is_salesman', 'pk' => $this->pk, 'text' => '是|否']])
            ->addExtraMap($extra_map)
            ->addJsUrl(['user'])
            ->addSearch([
                ['code__nickname__mobile', '会员编号/昵称/手机号', 'input,Like'],
                ['salesman_id', '业务员', 'select', array_replace([99999999 => '未分配'],\app\common\model\User::where(['is_salesman'=>1,'delete_time'=>0])->column('name', 'id'))]
            ])
            ->fetch('index');

    }

    public function save($param = [], $model = true): Json
    {
        return parent::save($this->request->post(), $model); // TODO: Change the autogenerated stub
    }

//    public static function getLevel(): array
//    {
//        return array_merge([0 => '暂无'], Level::column('title', 'id'));
//    }

    public static function getSalesman(): array
    {
        return array_replace([99999999 => '暂无'], \app\common\model\User::where(['is_salesman'=>1,'delete_time'=>0])->column('name', 'id'));
    }

    public function reset($type): Json
    {
        try {
            $ids = $this->request->post('ids');
            if ($type == 1) {
                $key = 'password';
                $value = md5('111111');
                $name = '登录密码';
            } else {
                $key = 'pay_password';
                $value = md5('222222');
                $name = '支付密码';
            }
            $this->model::update([$key => $value], ['id' => $ids]);
            $msg = '重置了【' . $name . '】会员标识ID【' . implode(',', $ids) . '】';
            Logs::adds($msg, $this->admin->id, $this->admin->admin_name);
            return json(['code' => 1, 'msg' => '已重置']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

    public function relation()
    {
        try {
            if ($this->request->isAjax()) {
                $id = $this->request->param('id');
                $list = $this->model::where('parent_id', $id)->field('id,code,nickname,mobile')->select();
                foreach ($list as &$v) {
                    $level = $v->level ? $v->level->title : '暂无';
                    $v['title'] = '编号【' . $v['code'] . '】
                    姓名【' . $v->nickname . '】
                    手机号【' . $v->mobile . '】
                    等级【' . $level . '】
                  ';
                }
                return json(['code' => 1, 'msg' => 'success', 'result' => $list]);
            }
            $keyword = $this->request->param('keyword');
            if ($keyword) {
                $map['code|nickname|mobile'] = $keyword;
            } else {
                $map['code'] = 'admin';
            }
            $first = $this->model::where($map)->field('id,code,nickname,mobile')->find();
            if ($first) {
                $level = $first->level ? $first->level->title : '暂无';
                $first['title'] = '编号【' . $first->code . '】
                姓名【' . $first->nickname . '】
                手机号【' . $first->mobile . '】
                等级【' . $level . '】
               ';
            }

            View::assign('first', $first);
            return View::fetch();

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

    public function login($id): Json
    {
        try {
            $user = $this->model::find($id);
            if ($user->token) {
                $token = $user->token;
            } else {
                $token = md5(time() . json_encode($user));
                $user->token = $token;
                $user->save();
            }
            cookie('token', $token);
            $description = '登录操作，会员【' . $user->code . '】';
            Logs::adds($description, $this->admin['id'], $this->admin['admin_name']);
            return json(['code' => 2, 'msg' => '登录成功', 'data' => ['code' => $user->code, 'url' => '/']]);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function agent()
    {
        $param = $this->request->param();
        View::assign('ids', $param['ids']);
        $salesman = \app\common\model\User::where(['is_salesman'=>1,'delete_time'=>0])->select();
        View::assign('salesman', $salesman);
//        dump($param);die;
        return View::fetch();
    }

    public function agent_save()
    {
        $param = $this->request->param();
        \app\common\model\User::whereIn('id',$param['ids'])->where(['is_salesman'=>0])->update(['salesman_id'=>$param['salesman_id']]);
        return json(['code' => 1, 'msg' => '设置成功']);
    }

    public function recharge()
    {
        $param = $this->request->param();
//        dump($param);die;
        if ($this->request->isAjax()) {
            switch ($param['type']) {
                case "get":
                    $user = $this->model::whereLike('code|mobile|nickname', '%' . $param['val'] . '%')
                        ->field('id,code,mobile,nickname')->select();
                    return json(['code' => 0, 'data' => $user]);
                case "account":
//                    dump($param);die;
                    $assets = Assets::where('uid', $param['id'])->find();
                    if ($assets) {
                        return json(['code' => 1, 'msg' => '', 'result' => $assets->$param['val']]);
                    } else {
                        return json(['code' => -1, 'msg' => '加载失败']);
                    }
                case "save":
                    try {
                        $this->validate($param, 'Recharge');
                    } catch (ValidateException $e) {
                        return json(['code' => -1, 'msg' => $e->getError()]);
                    }
                    return $this->model::recharge($param, $this->admin);
                default:
                    return json(['code' => -1, 'msg' => '加载失败']);
            }
        }
        View::assign('assets', Assets::getFields(3));
        return View::fetch();
    }

    public function delete($key = 'is_del'): Json
    {

        try {
            $id = $this->request->post($this->pk);
            $user = $this->model::where('id', $id)->find();
            if (empty($user)) {
                return json(['code' => -1, 'msg' => '会员不存在']);
            }
            if ($user->is_active == 2) {
                return json(['code' => -1, 'msg' => '会员已激活，无法删除']);
            }
            $count = Relation::where('uid', $user->id)->count();
            if ($count) {
                return json(['code' => -1, 'msg' => '该会员已推荐会员无法删除']);
            }
            Relation::destroy(['new_uid' => $user->id], true);
            $this->model::destroy(['id' => $user->id], true);

            Logs::adds('删除会员【' . $user->code . '】', $this->admin->id, $this->admin->admin_name);
            return json(['code' => 1, 'msg' => '已删除']);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }


    }


    public function import()
    {
        ini_set('memory_limit', '1024M');
        try{
            $excel = new Excel();
//            $file = request()->file('file');
//            $save_name = \think\facade\Filesystem::disk('public')->putFile( 'files', $file);
//            if($save_name)
//            {
//                $file_name = app()->getRootPath(). 'public/uploads/image' .$save_name;
//                $data = $excel->importExcel($file_name);
//            }
//            dump($savename);die;
            $title = [
                'B' => ['key' => 'numbers', 'title' => '保单号'],
                'C' => ['key' => 'org_code', 'title' => '管理机构代码'],
                'D' => ['key' => 'name', 'title' => '投保人'],
                'E' => ['key' => 'mobile', 'title' => '移动电话'],
//                'D' => ['key' => 'telephone', 'title' => '联系电话'],
                'F' => ['key' => 'protection_fee', 'title' => '险种应缴保费'],
                'G' => ['key' => 'life', 'title' => '险种缴费年限'],
            ];
            $data = $excel->importExcel($title);
//            unset($data[0], $data[1]);

            $coefficient_1 = Cache::get('system')['coefficient_1'];
            $coefficient_2 = Cache::get('system')['coefficient_2'];
            $coefficient_3 = Cache::get('system')['coefficient_3'];
            $coefficient_4 = Cache::get('system')['coefficient_4'];

            foreach ($data as $k => &$item) {
//                $num = \app\common\model\Import::where(['numbers'=>$item['numbers']])->count();
//                if(!$num)
//                {
                    $item['mobile'] = trim((string)$item['mobile']);
//                $item['numbers'] = date('YmdHis') . $item['mobile'] . rand(100000, 999999);
                    $user = \app\common\model\User::where(['mobile'=>$item['mobile']])->find();
                    $item['protection_fee'] = trim((string)$item['protection_fee']);
                    $item['life'] = trim((string)$item['life']);
                    $money = $item['protection_fee'];
                    if($item['life']==1)
                    {
                        $item['integral'] = round((float)$coefficient_1*$money);
                    }elseif($item['life']==3||$item['life']==4)
                    {
                        $item['integral'] = round((float)$coefficient_2*$money);
                    }elseif($item['life']>=5&&$item['life']<=9)
                    {
                        $item['integral'] = round((float)$coefficient_3*$money);
                    }elseif($item['life']>=10)
                    {
                        $item['integral'] = round((float)$coefficient_4*$money);
                    }

                    if($user)
                    {
                        if(!$user->name)
                        {
                            $user->name = $item['name'];
                            $user->save();
                        }
                        Target::Account()->basics($user->id, 'integral', $item['integral'], '导入增加', '+')
                            ->createNormal($user->id);
                    }else{
                        $param['code'] = generate(6, '', 1);
                        $token = md5(json_encode($user) . time() . $this->request->ip());
                        $param['token'] = $token;
                        $param['name'] = $item['name'];
                        $param['mobile'] = $item['mobile'];
                        $param['pay_password'] = md5('222222');
                        $res = \app\common\model\User::create($param);
                        Target::Account()->basics($res->id, 'integral', $item['integral'], '导入增加', '+')
                            ->createNormal($res->id);
                    }
//                $item['level'] = $item['disabled_level'];
//
//                if($item['reimburse_rate'] && $item['reimburse_rate'] <= 1){
//                    $item['reimburse_rate'] = (int)($item['reimburse_rate'] * 100);
//                }

                    $res = \app\common\model\Import::create($item);
//                }

            }

//            if ($res) {
//                return json(['code' => 1, 'msg' => '导入成功！']);
//            }
            return json(['code' => 1, 'msg' => '导入成功']);
        }catch (\Exception $e) {
            return json(['code' => -1, 'msg' =>  $e->getMessage()]);
        }

    }

}
